import os

from app import create_app

application = create_app(flask_config = 'local')
from app.extensions import db
from app.modules.agent.models import Agent
from app.modules.machine.models import Machine
from app.modules.common.utils import JsonFileUtil
from app.modules.common.dbUtil import createId


def getAgentList():
    _path = "/usr/local/Beetle/uCloud"
    _dir = os.listdir(_path)
    _list = []
    for file in _dir:
        _list.append(JsonFileUtil.load('%s/%s' % (_path, file)))
    return _list


def main():
    with application.app_context():
        _agents = getAgentList()
        if len(_agents) == 0:
            print 'ucloud agent is null'
            return

        _machine = Machine('172.16.1.1', 1, 1, 1)
        db.session.add(_machine)
        db.session.commit()
        _ips = []

        for _a in _agents:
            if str(_a['ip']) not in _ips:
                _agent = Agent(createId('ag'), str(_a['ip']), 1, '172.16.1.1', 'L')
                db.session.add(_agent)
                _ips.append(str(_a['ip']))
        db.session.commit()


if __name__ == '__main__':
    main()
